package cn.gzmli.dtt.common.controll;

import cn.gzmli.dtt.common.annotation.Comment;
import cn.gzmli.dtt.common.annotation.Privilege;
import cn.gzmli.dtt.common.config.cache.Config;
import cn.gzmli.dtt.common.entity.PageInfo;
import cn.gzmli.dtt.common.entity.Result;
import cn.gzmli.dtt.common.entity.Role;
import cn.gzmli.dtt.common.entity.User;
import cn.gzmli.dtt.common.entity.vo.ProjectVO;
import cn.gzmli.dtt.common.service.DepartmentService;
import cn.gzmli.dtt.common.service.UserService;
import cn.gzmli.dtt.common.utils.*;
import cn.gzmli.dtt.sbzyc.validation.Add;
import cn.gzmli.dtt.sbzyc.validation.Delete;
import cn.gzmli.dtt.sbzyc.validation.Update;
import com.xiaoleilu.hutool.util.StrUtil;
import jdk.nashorn.internal.ir.annotations.Ignore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Descript 用户相关接口
 * @Author xsx
 * @Date 2017/12/25
 */
@RestController
@RequestMapping("/user")
public class UserController implements BaseController<User> {
    @Autowired
    private UserService userService;
    @Autowired
    private DepartmentService departmentService;

    @Override
    @RequestMapping("/list")
    @ResponseBody
    @Comment("获取用户列表")
    public Result list() throws Exception {
        return new Result(Constant.SUCCESS, "获取用户列表成功", this.userService.getAll());
    }

    @Override
    @RequestMapping("/listByCondition")
    @ResponseBody
    @Comment("获取用户列表")
    public Result listByCondition(HttpServletRequest request, PageInfo pageInfo) throws Exception {
        List<Map<String, Object>> data = this.userService.getByCondition(request, pageInfo);
        return new Result(Constant.SUCCESS, "获取用户列表成功", data, pageInfo);
    }

    @Override
    @RequestMapping("/get")
    @ResponseBody
    @Comment("获取用户信息")
    public Result get(Integer id) throws Exception {
        return new Result(Constant.SUCCESS, "获取用户信息成功", this.userService.get(id));
    }

    @Override
    @RequestMapping("/getByCondition")
    @ResponseBody
    @Comment("获取用户信息")
    public Result getByCondition(HttpServletRequest request) throws Exception {
        Map<String, String> condition = new HashMap<>();
        return new Result(Constant.SUCCESS, "获取用户信息成功", this.userService.getByCondition(condition));
    }

    @Override
    @RequestMapping("/save")
    @ResponseBody
    @Comment("新增用户信息")
    @Privilege("/user/save")
    public Result save(@Validated(Add.class) User user) throws Exception {
        User _user = userService.save(user);
        if (_user == null){
            return new Result(Constant.FAIL, "用户名已存在");
        }
        else{
            return new Result(Constant.SUCCESS, "新增用户信息成功", _user);
        }

    }

    @Override
    @RequestMapping("/update")
    @ResponseBody
    @Comment("修改用户信息")
    @Privilege("/user/update")
    public Result update(@Validated(Update.class) User user) throws Exception {
        this.userService.update(user);
        return new Result(Constant.SUCCESS, "修改用户信息成功");
    }

    @RequestMapping("/addOrUpdateOrgRole")
    @ResponseBody
    @Comment("更新用户机构角色信息")
    @Privilege("/user/addOrUpdateOrgRole")
    public Result addOrUpdateOrgRole(Integer id, String orgIDs, String roleIDs) throws Exception {
        userService.addOrUpdateOrgRole(id, orgIDs, roleIDs);
        return new Result(Constant.SUCCESS, "更新用户机构角色信息成功");
    }

    @Override
    @RequestMapping("/delete")
    @ResponseBody
    @Comment("删除用户信息")
    @Privilege("/user/delete")
    public Result delete(@Validated(Delete.class) User user) throws Exception {
        this.userService.delete(user);
        return new Result(Constant.SUCCESS, "删除用户信息成功");
    }

    @RequestMapping("/updateStatus")
    @ResponseBody
    @Comment("更新用户状态")
    @Privilege("/user/updateStatus")
    public Result updateStatus(User user) throws Exception {
        int r = this.userService.updateStatus(user);
        return new Result(r, r > 0 ? "更新用户状态成功" : "更新用户状态失败");
    }

    @RequestMapping("/updateHeaderPath")
    @Privilege("/user/updateHeaderPath")
    @Comment("更新用户头像")
    public Result updateHeaderPath(HttpServletRequest request, Integer userId, String headerpath) throws Exception {
        int r = this.userService.updateHeaderPath(Config.getUser(request).getId(), headerpath);
        User sessionUser = Config.getUser(request);
        sessionUser.setHeaderpath(headerpath);
        request.getSession().setAttribute("User", sessionUser);
        return new Result(r, r > 0 ? "更新用户头像成功" : "更新用户头像失败");
    }

    @RequestMapping("/updateRoles")
    @ResponseBody
    @Comment("更新用户角色")
    @Privilege("/user/updateRoles")
    public Result updateRoles(HttpServletRequest request, Integer id, String roleIDS) throws Exception {
        this.userService.updateRoles(request, id, roleIDS);
        return new Result(Constant.SUCCESS, "更新用户角色成功");
    }

    @RequestMapping("/listTree")
    @ResponseBody
    @Ignore
    public Result listTree(HttpServletRequest request) throws Exception {
        List<Map<String, Object>> data = new ArrayList<>();
        data.addAll(this.userService.getTree(request));
        if (StrUtil.isNotBlank(request.getParameter("isProjectUser"))) {
            List<Map<String, Object>> departments = this.departmentService.getTree(request);
            Collections.sort(departments, new ComMapObjCompatator("orderNo"));
            data.addAll(departments);
        }
        return new Result(Constant.SUCCESS, "获取用户列表成功", data);
    }

    @Override
    public Result lists(HttpServletRequest request, PageInfo pageInfo) throws Exception {
        // TODO Auto-generated method stub
        return null;
    }

    @RequestMapping("/getCurrentUser")
    @ResponseBody
    @Ignore
    public Result getCurrentUser(HttpServletRequest request) throws Exception {
        User user = (User)Config.getUser(request).clone();
        Set<Role> roleSet = user.getRoles();
        if (roleSet != null){
            for (Role role : roleSet) {
                role.setMenus(null);
            }
        }
        return new Result(Constant.SUCCESS, "获取当前用户信息成功", user);
    }

    @RequestMapping("/updatePassword")
    @ResponseBody
    @Comment("修改用户密码")
    @Privilege("/user/updatePassword")
    public Result updatePassword(HttpServletRequest request, String oldPassword, String newPassword) throws Exception {
        return this.userService.updatePassword(Config.getUser(request), oldPassword, newPassword);
    }

    /**
     * 获取用户机构角色信息列表
     *
     * @param request
     * @param userIds
     * @return
     * @throws Exception 20180716
     * @author wonderful
     */
    @RequestMapping("/listUsersOrgs")
    @ResponseBody
    @Comment("获取用户机构信息列表")
    @Privilege("/user/listUsersOrgs")
    public Result listUsersOrgs(HttpServletRequest request, String userIds) throws Exception {
        List<Map<String, Object>> usersOrgs = userService.queryUsersOrgs(userIds);
        return new Result(Constant.SUCCESS, "获取用户机构信息列表完成。", usersOrgs);
    }

    /**
     * 获取用户机构角色信息列表
     *
     * @param request
     * @param userIds
     * @param orgIds
     * @return
     * @throws Exception 20180713
     * @author wonderful
     */
    @RequestMapping("/listUsersOrgsRoles")
    @ResponseBody
    @Comment("获取用户机构角色信息列表")
    @Privilege("/user/listUsersOrgsRoles")
    public Result listUsersOrgsRoles(HttpServletRequest request, String userIds, String orgIds) throws Exception {
        List<Map<String, Object>> usersOrgsRoles = userService.queryUsersOrgsRoles(userIds, orgIds);
        return new Result(Constant.SUCCESS, "获取用户机构角色信息列表完成。", usersOrgsRoles);
    }

    @RequestMapping("/changeUserOrgsRoles")
    @ResponseBody
    @Comment("更改用户机构角色")
    @Privilege("/user/changeUserOrgsRoles")
    public Result changUserOrgsRoles(HttpServletRequest request, Integer userId, String userOrgsRolesStr) throws Exception {

        List<Map> usersOrgsRoles = BaseUtil.isNotEmpty(userOrgsRolesStr) ? JsonUtils.toBeanList(userOrgsRolesStr, Map[].class) : null;
        if (userService.insertOrUpdateUserOrgsRoles(userId, usersOrgsRoles)) {
            return new Result(Constant.SUCCESS, "更改用户机构角色成功。");
        } else {
            return new Result(Constant.SUCCESS, "更改用户机构角色失败!");
        }

    }

    /**
     * 获取用户机构角色信息列表
     *
     * @param request
     * @param userIds
     * @return
     * @throws Exception 20180717
     * @author wonderful
     */
    @RequestMapping("/listUsersProjects")
    @ResponseBody
    @Comment("获取用户项目信息列表")
    @Privilege("/user/listUsersProjects")
    public Result listUsersProjects(HttpServletRequest request, String userIds) throws Exception {
        List<Map<String, Object>> usersProjecs = userService.queryUsersProjects(userIds);
        return new Result(Constant.SUCCESS, "获取用户项目标段信息列表完成。", usersProjecs);
    }

    /**
     * 获取用户机构角色信息列表
     *
     * @param request
     * @param userIds
     * @param projectIds
     * @return
     * @throws Exception 20180713
     * @author wonderful
     */
    @RequestMapping("/listUsersProjectsSections")
    @ResponseBody
    @Comment("获取用户项目标段信息列表")
    @Privilege("/user/listUsersProjectsSections")
    public Result listUsersProjectsSections(HttpServletRequest request, String userIds, String projectIds) throws Exception {
        List<Map<String, Object>> usersProjectsSections = userService.queryUsersProjectsSections(userIds, projectIds);
        return new Result(Constant.SUCCESS, "获取用户项目标段信息列表完成。", usersProjectsSections);
    }

    @RequestMapping("/changUserProjectsSections")
    @ResponseBody
    @Comment("更改用户项目标段")
    @Privilege("/user/changUserProjectsSections")
    public Result changUserProjectsSections(HttpServletRequest request, Integer userId, String userProjectsSectionsStr) throws Exception {

        List<Map> usersProjectsSections = BaseUtil.isNotEmpty(userProjectsSectionsStr) ? JsonUtils.toBeanList(userProjectsSectionsStr, Map[].class) : null;
        if (userService.insertOrUpdateUserProjectsSections(userId, usersProjectsSections)) {
            return new Result(Constant.SUCCESS, "更改用户项目标段成功。");
        } else {
            return new Result(Constant.SUCCESS, "更改用户项目标段失败!");
        }

    }

    /**
     * 列出用户所属机构
     * @author wondeful
     * @date 220180805
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/listUserOrgs")
    @ResponseBody
    public Result listUserOrgs(HttpServletRequest request) throws Exception {
        User curUser=Config.getUser(request);
        return new Result(Constant.SUCCESS, "获取用户所属机构成功",  curUser.getUserOrg());
    }

    /**
     * 列出用户所属机构
     * @author wondeful
     * @date 220180805
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/listUserProjects")
    @ResponseBody
    public Result listUserProjects(HttpServletRequest request) throws Exception {
        User curUser=Config.getUser(request);
        return new Result(Constant.SUCCESS, "获取用户所属机构成功",  curUser.getUserProject());
    }

    /**
     * 列出用户所属机构
     * @author wondeful
     * @date 220180805
     * @param request
     * @param projectIds
     * @return
     * @throws Exception
     */
    @RequestMapping("/listUserSections")
    @ResponseBody
    public Result listUserSections(HttpServletRequest request, String projectIds) throws Exception {
        User curUser=Config.getUser(request);
        List<ProjectVO> userProjectSectionByCond=new ArrayList<ProjectVO>();
        List<ProjectVO> userProjectSections=curUser.getUserProjectSection();
        if(BaseUtil.isNotEmpty(projectIds)){
            String[] projectIdsArray=null;
            if(projectIds.indexOf(",")!=-1) {
               projectIdsArray = projectIds.split(",");
            }else{
                projectIdsArray=new String[]{projectIds};
            }

            for(String projectId:projectIdsArray){
                for(ProjectVO projectVO:userProjectSections){
                      if(projectId.equals(projectVO.getProjectId().toString())){
                          userProjectSectionByCond.add(projectVO);
                      }
                }
            }
            return new Result(Constant.SUCCESS, "获取用户所属标段成功", userProjectSectionByCond);
        }else{
            return new Result(Constant.SUCCESS, "获取用户所属标段成功",userProjectSections);
        }

    }


    @RequestMapping("/setUserCurrentProject")
    @ResponseBody
    @Comment("更改用户当前项目")
    @Privilege("/user/setUserCurrentProject")
    public Result setUserCurrentProject(HttpServletRequest request, Integer projectId) throws Exception {
        User user = Config.getUser(request);
        user.setUserCurrentProjectId(projectId);
        return new Result(Constant.SUCCESS, "更改用户当前项目");
    }

    @RequestMapping("/getUsersByIds")
    @ResponseBody
    @Comment("获取多个用户信息")
    public Result getUsersByIds(String userIds) throws Exception {
        if (BaseUtil.isNotEmpty(userIds)) {
            return new Result(Constant.SUCCESS, "获取多个用户信息", userService.getUsersByIds(userIds));
        } else {
            return new Result(Constant.FAIL, "用户IDS为空！");
        }
    }
}
